package com.huan.pdf.controller;

import com.huan.pdf.utils.FreemarkerUtils;
import com.huan.pdf.utils.Pdf2PicUtil;
import com.huan.pdf.utils.PdfUtils;
import org.apache.pdfbox.io.IOUtils;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * pdf控制器
 *
 * @author admin
 */
@RestController
public class PdfController {
    @GetMapping("pdf")
    public void pdf(HttpServletResponse response) throws IOException {

        Map<String, Object> params = new HashMap<>(16);
        params.put("mainTitle", "这是一个标题 - " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        params.put("base64Img", "data:image/jpeg;base64," + Base64Utils.encodeToString(IOUtils.toByteArray(PdfController.class.getClassLoader().getResourceAsStream("static/base64.jpg"))));

        // 渲染模板
        String htmlContent = FreemarkerUtils.processTemplate("pdf.ftl", params);
        // 生成pdf
        PdfUtils.generatePdf(htmlContent, response);
    }

    /**
     * 将pdf转换成图片并通过zip进行下载
     */
    @GetMapping("downloadPdfImg")
    public void downloadPdfImg(HttpServletResponse response) throws IOException {
        response.reset();
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition",
                "attachment; filename=" +
                        URLEncoder.encode("pdf转图片.zip", StandardCharsets.UTF_8.name()));

        Map<String, Object> params = new HashMap<>(16);
        params.put("mainTitle", "这是一个标题 - " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        // data:image/jpeg;base64, 这个前缀不可少
        params.put("base64Img", "data:image/jpeg;base64," + Base64Utils.encodeToString(IOUtils.toByteArray(PdfController.class.getClassLoader().getResourceAsStream("static/base64.jpg"))));
        // 渲染模板
        String htmlContent = FreemarkerUtils.processTemplate("pdf.ftl", params);
        // 转换成pdf字节流
        byte[] pdfBytes = PdfUtils.toPdfBytes(htmlContent);

        byte[] zipBytes = Pdf2PicUtil.toZipBytes(pdfBytes, "img");
        response.setContentLength(zipBytes.length);
        try (ServletOutputStream out = response.getOutputStream()) {
            out.write(zipBytes);
            out.flush();
        }
    }
}
